package com.jess.arms.base.my;

import android.net.ParseException;

import com.google.gson.JsonIOException;
import com.google.gson.JsonParseException;
import com.jess.arms.mvp.IView;

import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.net.UnknownServiceException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;

/**
 * ================================================
 * author : Alex
 * version: 3.2.0
 * Description:
 * <p>
 * Created by ErrorBook on 2021/1/5.
 * ================================================
 */
public abstract class BaseSubscriber<T> implements Observer<BaseEntity<T>> {

    private final IView mRootView;

    public BaseSubscriber(IView mRootView) {
        this.mRootView = mRootView;
    }

    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onNext(BaseEntity<T> tBaseEntity) {
        if (tBaseEntity.isSuccess()) {
            onRequestSuccess(tBaseEntity.getData());
        } else {
            onRequestError(tBaseEntity.getMsg());
        }
    }

    @Override
    public void onError(Throwable t) {
            if (t instanceof UnknownHostException || t instanceof ConnectException || t instanceof UnknownServiceException) {
                mRootView.showNoNetwork();
            } else if (t instanceof SocketTimeoutException) {
                mRootView.showTimeOut();
            } else if (t instanceof HttpException) {
                mRootView.showFailure();
            } else if (t instanceof JsonParseException || t instanceof ParseException || t instanceof JSONException || t instanceof JsonIOException) {
                mRootView.showFailure();
            } else {
                mRootView.showFailure();
            }

        onRequestError(t.getMessage());
    }

    @Override
    public void onComplete() {

    }


    protected abstract void onRequestSuccess(T data);

    protected abstract void onRequestError(String data);
}
